# -*- coding: utf-8 -*-
import requests
from requests.exceptions import RequestException
from pyquery import PyQuery as pq

def get_chapter_urlList(url):
    try:
        response=requests.get(url)
        doc=pq(response.text)
        results_list=doc("#content-list .book-list")
        results=pq(results_list[0])("ul li a")
        chapter_list=[]
        for result in results:
            chapter_list.append([result.text,pq(result).attr.href])
        return chapter_list
    except RequestException:
        return None

def get_chapter_content(li):
    story=""
    for item in li:
        try:
            response=requests.get(item[1])
            story=story+item[0]+"\n"
            response.encoding="utf-8"
            doc=pq(response.text)
            results=doc("#pagewrap > article > p")
            for result in results:
                story=story+result.text+"\n"
        except RequestException:
            return None
        finally:
            with open("story.txt","w",encoding="utf-8") as f:
                f.write(story)
                f.close()
if __name__ == '__main__':
    chapter_list=get_chapter_urlList("http://www.luoxia.com/muyun/#myj-xs")
    get_chapter_content(chapter_list)